package cn.orange.ch07_binarytree;

import cn.orange.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * LC515.在每个树行中找最大值
 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值
 */
public class LC515 {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> que = new LinkedList<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode poll = que.poll();
                max = Math.max(max, poll.val);
                if (poll.left != null) {
                    que.offer(poll.left);
                }
                if (poll.right != null) {
                    que.offer(poll.right);
                }
            }
            res.add(max);
        }
        return res;
    }
    public static void main(String[] args) {
        LC515 alg = new LC515();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(3);
        root.right = new TreeNode(2);
        root.right.right = new TreeNode(9);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(3);
        System.out.println(alg.largestValues(root));
    }
}
